//
//  AccountViewModel.swift
//  weibo92
//
//  Created by Apple on 15/10/28.
//  Copyright © 2015年 miao. All rights reserved.
//

import UIKit
//MARK 用户账号视图模型，没有继承关系
class AccountViewModel {
    
    ///账户模型
    var account: AccountModel?
     // 单例：保证只加载一次，不用多次从磁盘加载，提高性能。
    static let shareAccountViewModel = AccountViewModel()
    
    ///设置没有过期的token
    var accessToken:String? {
        //如果token过期 ，则返回nil
        if !isExpired {
            return account?.access_token
        }
        
        return nil
    }
    
    
    var userLogon: Bool {
        // 如果token != nil,  则登录成功
        //如果 token 不过期则登录成功
        return account?.access_token != nil && !isExpired  
    }
    ///账户存储路径，计算型属性
    private var accountPath: String{
        ///一定能取到磁盘路径
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        
        return (path as NSString).stringByAppendingPathComponent("userAccount.plist")
    }
    /// 是否过期
    private var isExpired:Bool{
        
        ///没有过期,  过期日期   当前日期
//        account?.expiresDate = NSDate(timeIntervalSinceNow: -3600)
//        print(account?.expiresDate)
        
        if account?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
            
            return false
        }
        ///过期
        return true
    }
    ///构造函数
    private init(){
        ///从沙盒中解档数据
        account =  NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? AccountModel
        
        /// 判断token 是否过期
        if isExpired {
            print("token过期")
            account = nil
        }
        
        //print(account)
    }

}

//MARK:  -加载token 获得用户信息
extension AccountViewModel{
    
    //MARK: 加载token
     func loadAccessToken(code:String, finished:(isSuccess:Bool) -> ()){
        NetworkTools.shareTools.loadAccessToken(code) { (result, error) -> () in
            if error != nil{
                finished(isSuccess: false)
                return
            }
            
            self.account = AccountModel(dict: result as! [String:AnyObject])
            
            self.loadAccountInfo(self.account!,finished:finished)
        }
    }
     //MARK:  加载用户信息
    private func loadAccountInfo(account:AccountModel, finished:(isSuccess:Bool) -> ()){
        NetworkTools.shareTools.loadUserAccountInfo(account.uid!) { (result, error) -> () in
            if error != nil{
                finished(isSuccess: false)
                return
            }
            //print(result!)
            
            guard let dict = result as? [String: AnyObject] else{
                finished(isSuccess: false)
                return
            }
            //            print(dict["screen_name"])
            //            print(dict["avatar_large"])
            ///保存对象（前，应该在模型里定义需要保存的属性）
            account.avatar_large = dict["avatar_large"] as? String
            account.screen_name = dict["screen_name"] as? String
            
            NSKeyedArchiver.archiveRootObject(account, toFile: AccountViewModel.shareAccountViewModel.accountPath)
            
            // 成功回调
            finished(isSuccess: true)
            print(AccountViewModel.shareAccountViewModel.account)
        }
    }
}